/*
 * Copyright (C) 2011 by Fabien Barbero
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.flickr.api;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Fabien Barbero
 */
public class LocalCacheImpl implements LocalCache {

    private static final Logger LOGGER = LoggerFactory.getLogger(LocalCacheImpl.class);
    private static GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    
    private final Map<URL, BufferedImage> cache = new HashMap<URL, BufferedImage>();
    
    @Override
    public synchronized BufferedImage getImage(URL url) {
        if(url == null) {
            return null;
        }
        
        BufferedImage img = cache.get(url);
        if(img == null) {
            InputStream is = null;
            try {
                long start = System.currentTimeMillis();
                URLConnection conn = url.openConnection();
                int length = conn.getContentLength();
                is = conn.getInputStream();
                
                img = toCompatibleImage(ImageIO.read(url));
                cache.put(url, img);
                
                if(LOGGER.isDebugEnabled()) {
                    long duration = System.currentTimeMillis() - start;
                    LOGGER.debug("Image downloaded in {}ms ({}bytes)", duration, length);
                }
                
            } catch (IOException ex) {
                LOGGER.warn("Error reading image on URL " + url.toExternalForm(), ex);
                return null;
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
        return img;
    }
    
    private BufferedImage toCompatibleImage(BufferedImage image) {
        BufferedImage compatibleImage = configuration.createCompatibleImage(image.getWidth(),
                image.getHeight(), Transparency.TRANSLUCENT);
        Graphics g = compatibleImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return compatibleImage;
    }

    @Override
    public BufferedImage getImage(String url) {
        try {
            return getImage(new URL(url));
        } catch (MalformedURLException ex) {
            LOGGER.warn("Error reading image on URL " + url, ex);
                return null;
        }
    }
    
    @Override
    public synchronized void clear() {
        cache.clear();
    }
    
}
